
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using GruntXProductions;
using Viper;
using Viper.Opcodes;

namespace Diamond
{
	public class Compiler
	{
		public static Assembly Program;
		public static Lexer Scanner;
		public static bool OutputIL = false;
        public static string Output;
		public static void Main (string[] args)
		{
            CodeGen.Assembler = new Assembly();
            Parser parser;
            CodeGen cgen;
            if (args.Length == 0)
            {
                Console.Error.WriteLine("No input!");
                return;
            }
            Output = System.IO.Path.GetFileNameWithoutExtension(args[0]) + ".gex";
            for (int i = 1; i < args.Length; i++)
            {
                if (args[i] == "-o")
                {
                    ++i;
                    Output = args[i];
                }
				else if(args[i] == "-s")
					OutputIL = true;
            }
            Scanner = new Lexer();
            cgen = new CodeGen();
			Scanner.ScanWhiteSpaces = true;
            try
            {
                Scanner.Scan(new StringReader(File.ReadAllText(args[0])));
                parser = new Parser(Scanner.tokens);
                parser.Parse();
                cgen.BeginGeneration(parser.AST);
            }
            catch (ParserException ex)
            {
                Console.Error.WriteLine("Fatal error during parsing: " + ex.Error);
                return;
            }
            catch (CodeGenException ex)
            {
                Console.Error.WriteLine(ex.Error);
                foreach (string str in cgen.Errors)
                {
                    Console.Error.WriteLine("Error: " + str.ToString());
                }
                return;
            }
            catch (Exception exp)
            {
                Console.Error.WriteLine("Fatal error: " + exp.Message);
                return;
            }
			if(OutputIL)
			{
				foreach(Instruction IL in CodeGen.Assembler.innerCode)
				{
					Console.WriteLine(IL.Mnemonic + " " + IL.Operand);
				}
			}
			CodeGen.Assembler.Merge(GEX.Open("coreLib.gex"));
			CodeGen.Assembler.SaveGEX(Output);
		}
		
	}
}

/*
 *  4 + 4 == 5 + 5 
 * 
 * Add (4, 4) 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 */